﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.MenuCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.MenuHandler
{
    public class DelMenuHandler : IRequestHandler<DelMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenuManagement> _baseRepository;
        private readonly IMapper _mapper;

        public DelMenuHandler(IBaseRepository<MenuManagement> baseRepository, IMapper mapper)
        {
            _baseRepository = baseRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.Success;
            result.Msg = "删除成功";

            var entity = _baseRepository.GetAll().Where(p => p.MenuId == request.MenuId || p.ParentId == request.MenuId).ToList();

            await _baseRepository.DelRang(entity);
            return await Task.FromResult(result);
    //        var entity = _mapper.Map<MenuManagement>(request);

    //        var model = _baseRepository.GetAll()
    //.Where(p => p.MenuId ==request.MenuId)
    //.ToList();

    //        try
    //        {
    //            if (entity.ParentMenuName==request.MenuName)
    //            {
    //                // 标记要删除的实体为已删除
    //                foreach (var item in model)
    //                {
    //                    item.IsDeleted = true;
    //                }

    //                // 批量删除
    //                await _baseRepository.DelRang(model);

    //                result.Code = APIEnum.Success;
    //                result.Msg = "批量删除成功";
    //            }
    //            else if(entity.MenuId==request.MenuId)
    //            {
    //                    entity.IsDeleted = true;
    //                    _baseRepository.Del(entity);
    //                    result.Code = APIEnum.Success;
    //                    result.Msg = "单个删除成功";
    //                }
    //                else
    //                {
    //                    result.Code = APIEnum.Failed;
    //                    result.Msg = "未找到要删除的记录";
    //                }
    //        }
    //        catch (Exception ex)
    //        {
    //            result.Code = APIEnum.Failed;
    //            result.Msg = $"删除失败: {ex.Message}";
    //        }

    //        return result;
        }
    }
}
